package com.chalk.common.pay.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.chalk.common.util.Result;

import java.util.HashMap;
import java.util.Map;

import static com.chalk.common.pay.ali.AliPayUtil.*;

public class AliPay {


    /**
     * 支付(支付宝)
     * @return
     * @throws AlipayApiException
     */
    public static Result Pay(AlipayTradeAppPayModel model ,String orderId){

        //沙箱 https://openapi.alipaydev.com/gateway.do
        //正式 https://openapi.alipay.com/gateway.do
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。

        request.setBizModel(model);
        request.setNotifyUrl(NOTIFY_URL);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                String body = response.getBody();
                Map<String,Object> map = new HashMap<>();
                map.put("body",body);
                map.put("orderId",orderId);
                return Result.success(map);
            }
            //就是orderString 可以直接给客户端请求，无需再做处理。
            System.out.println(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.fail("支付失败");
    }


}
